#!/usr/bin/env python3
"""
仓颉仓库管理工具
提供 CLI 接口管理所有仓颉仓库，并支持一键创建 Issue 和 PR
"""
import click
import sys
from pathlib import Path

# 添加当前目录到路径
sys.path.insert(0, str(Path(__file__).parent))

import console  # noqa: F401  # 启用彩色提示

from config import Config
from i18n import set_language as set_runtime_language

from commands import repo, upload
from commands.cherry_pick import cherry_pick
from commands.version import version as version_cmd, print_version
from commands.help import help as help_cmd, get_help_text
from commands.config import config as config_cmd
from commands.update import update as update_cmd


class CustomGroup(click.Group):
    """自定义 Group 类，使用 help.py 中的帮助文本"""
    def format_help(self, ctx, formatter):
        formatter.write(get_help_text())


def _initialize_language():
    if getattr(_initialize_language, "_done", False):
        return
    cfg = Config()
    set_runtime_language(cfg.get_language())
    _initialize_language._done = True


@click.group(cls=CustomGroup, invoke_without_command=True, context_settings={'help_option_names': ['-h', '--help']})
@click.option('--version', '-v', is_flag=True, help='显示版本信息')
@click.pass_context
def cli(ctx, version):
    """仓颉仓库管理工具"""
    _initialize_language()
    if version:
        print_version()
        ctx.exit()
    # 如果没有子命令，显示帮助信息
    if ctx.invoked_subcommand is None:
        click.echo(get_help_text())


# 注册子命令（直接注册，不使用 repo 子命令）
cli.add_command(repo.init, name='init')
cli.add_command(repo.add, name='add')
cli.add_command(repo.remove, name='remove')
cli.add_command(repo.sync, name='sync')
cli.add_command(repo.status, name='status')
cli.add_command(repo.start, name='start')
cli.add_command(repo.checkout, name='checkout')
cli.add_command(upload.upload, name='upload')
cli.add_command(cherry_pick, name='cherry-pick')
cli.add_command(version_cmd, name='version')
cli.add_command(help_cmd, name='help')
cli.add_command(config_cmd, name='config')
cli.add_command(update_cmd, name='update')


if __name__ == '__main__':
    cli()

